package com.shiguo365.market.display.activity;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.recker.flybanner.FlyBanner;
import com.shiguo365.market.application.MyApplication;
import com.shiguo365.market.display.base.BaseActivity;
import com.shiguo365.market.display.listener.NavigationFinishClickListener;
import com.shiguo365.market.display.util.ActivityCollector;
import com.shiguo365.market.R;
import com.shiguo365.market.display.util.ToastUtils;
import com.shiguo365.market.display.view.IDetailView;
import com.shiguo365.market.presenter.implement.DetailPresenter;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by caomenglong on 16/7/8.
 */
public class DetailActivity extends BaseActivity implements IDetailView {

    private static final String TAG = "DetailActivity";

    DetailPresenter detailPresenter;

    private FlyBanner mBannerNet;//加载网络图片
    private WebView webView;

    private String pid = "";

    @BindView(R.id.textViewDatailProductName)
    protected TextView mTvDatailProductName;

    @BindView(R.id.textViewDatailSpecName)
    protected TextView mTvDatailSpecName;

    @BindView(R.id.textViewInventory)
    protected TextView mTvInventory;

    @BindView(R.id.textViewPrice1)
    protected TextView mTvViewPrice1;

    @BindView(R.id.textViewTitle2)
    protected TextView mTvViewTitle2;

    @BindView(R.id.textViewPrice2)
    protected TextView mTvViewPrice2;

    @BindView(R.id.textViewTitle3)
    protected TextView mTvViewTitle3;

    @BindView(R.id.textViewPrice3)
    protected TextView mTvViewPrice3;

    @BindView(R.id.webViewdetail)
    protected WebView mWbDetail;

    @BindView(R.id.product_detail_toolbar)
    protected Toolbar toolbar;


    @BindView(R.id.detailbanner)
    protected FlyBanner mFlybanner;

    @BindView(R.id.detailnavbar) RelativeLayout mRldetailnavbar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        ButterKnife.bind(this);
        toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this));
        Intent intent =getIntent();
        pid=intent.getStringExtra("productId");

        mRldetailnavbar.bringToFront();

        detailPresenter = new DetailPresenter(this,this);

        //initNetBanner();
        //webView = (WebView) findViewById(R.id.webViewdetail);

//        WebSettings webSettings = mWbDetail.getSettings();
//
//        webSettings.setUseWideViewPort(true);//关键点
//        webSettings.setLoadWithOverviewMode(true);



        ActivityCollector.addActivity(this);

        detailPresenter.getdetail(pid);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }


    /**
     * 加载网页图片
     */
    private void initNetBanner() {
        mBannerNet = (FlyBanner) findViewById(R.id.detailbanner);

        String[] mImagesUrl = {
                "http://7xj380.com1.z0.glb.clouddn.com/2016-07-03_5778d0726ac00.png",
                "http://7xj380.com1.z0.glb.clouddn.com/2016-07-03_5778d43571e6e.png",
                "http://7xj380.com1.z0.glb.clouddn.com/2016-07-03_5778e8177ea01.png",
                "http://7xj380.com1.z0.glb.clouddn.com/2016-06-30_577479528ff61.png"
        };

        List<String> imgesUrl = new ArrayList<>();
        for (int i = 0; i < mImagesUrl.length; i++) {
            imgesUrl.add(mImagesUrl[i]);
        }
        mBannerNet.setImagesUrl(imgesUrl);

        mBannerNet.setOnItemClickListener(new FlyBanner.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                toast("点击了第" + position + "张图片");
            }
        });
    }

    private void toast(String str) {
        Toast.makeText(DetailActivity.this, str, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onGetDetailInfoOk(@NonNull JSONObject detailinfo) {
        Log.d(TAG,detailinfo.toJSONString());
        //mPid.setText(detailinfo.getInteger("id"));
        toolbar.setTitle(detailinfo.getString("name"));
        mTvDatailProductName.setText(detailinfo.getString("name"));
        mTvDatailSpecName.setText(detailinfo.getString("quantity"));

        JSONObject morebuy = detailinfo.getJSONObject("more_buy");

        int num1 = 0;
        int price1 = 0;
        int num2 = 0;
        int price2 = 0;
        if(morebuy.size() > 0){
            //没有设阶梯价格
            num1 = morebuy.getInteger("num1");
            price1 = morebuy.getInteger("price1");
            num2 = morebuy.getInteger("num2");
            price2 = morebuy.getInteger("price2");
        }

        if(num1 > 0){
            mTvViewTitle2.setText(">"+String.valueOf(num1)+"件");
            mTvViewPrice2.setText(String.valueOf(price1)+"元");
        }

        if(num2 > 0){
            mTvViewTitle3.setText(">"+String.valueOf(num2)+"件");
            mTvViewPrice3.setText(String.valueOf(price2)+"元");
        }

        String str = detailinfo.getString("picurlarray");
        String[] mImagesUrl = str.replace("[","").replace("]","").replace("\"","").replace("\\","").split(",");
        List<String> imgesUrl = new ArrayList<>();
        for (int i = 0; i < mImagesUrl.length; i++) {
            imgesUrl.add(mImagesUrl[i]);
        }

        mFlybanner.setImagesUrl(imgesUrl);
        mTvViewPrice1.setText(detailinfo.getString("price")+"元");

        int inv = detailinfo.getInteger("inventory");
        mTvInventory.setText(String.valueOf(inv)+"件");
        Log.d(TAG,"测试====>");
        String content = detailinfo.getString("content");

        String cssstr="<style>"+
                   "img{" +
                         "max-width:100%;" +
                        "height:auto}" +
        "video{"+
                           "max-width:100%;"+
                           "height:auto}"+
                 "</style>" ;

        String jsstr="<script type=\"text/javascript\">"+
        "var imgs = document.getElementsByTagName('img');" + // 找到table标签
                "for(var i = 0; i<imgs.length; i++){" +  // 逐个改变
                "imgs[i].style.width = '100%';" +  // 宽度改为100%
                "imgs[i].style.height = 'auto';" +
                "}" +
                "</script>";

        String customHtml = "<html>"+cssstr+"<body>"+content+jsstr+"</body></html>";


        mWbDetail.loadData(customHtml, "text/html", "UTF-8");
        //自适应屏幕
        mWbDetail.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWbDetail.getSettings().setLoadWithOverviewMode(true);

//        mWbDetail.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//        mWbDetail.getSettings().setUseWideViewPort(true);




        return true;
    }

    @Override
    public void showDetailMessages(String msg) {
        ToastUtils.with(this).show(msg);
    }


    @OnClick(R.id.buttonAddCart)
    public void addDetailCart(){

        int uid = MyApplication.getUID();

        detailPresenter.addDetailCart(uid,pid);
    }

    @OnClick(R.id.goCart)
    public void goCart(){
        Intent intent =new Intent(this,MainActivity.class);
        intent.putExtra("FragmentId",R.id.txt_cart);
        startActivity(intent);
        //finish();
    }
}
